<?php


namespace app\miniProgram\controller;


use app\home\severs\OutReceiptSever;
use app\miniProgram\model\MaterialKucunView;
use think\Exception;
use think\facade\Db;

class OutReceipt extends Auth
{
    protected $table='out_receipt';
    public function onSure()
    {
      $validate=new \app\miniProgram\validate\Action();
      if (!$validate->scene('sureOutReceipt')->check($this->param)){
          return $this->jump(0,$validate->getError());
      }
      $where1[]=['wId','=',$this->param['wId']];
      $where1[]=['mdId','=',$this->param['mdId']];
      $info=MaterialKucunView::actionInfo($where1);
      if (!$info){
          return $this->jump(0,'参数有误');
      }
      $hasNum=$info['countNum']-$info['sendNum'];
      if ($hasNum<$this->param['num']){
          return $this->jump(0,'库存不足');
      }
      Db::connect('company')->startTrans();
      try{
          $printCompany=config('config.companyName');
          $wCode=Db::connect('company')->name('warehouse')->where('id',$this->param['wId'])->value('wCode');
          $ordernum=$this->getDJBHBuySql($this->table,'orderNum',$wCode);
          $outData=[
              'type'=>$this->param['type'],
              'outTime'=>$this->param['outTime']??date('Y-m-d'),
              'status'=>$this->param['status']??1,
              'punter_id'=>$this->param['punter_id']??0,
              'printCompany'=>$this->param['printCompany']??$printCompany[0],
              'orderNum'=>$ordernum,
              'create_time'=>time(),
              'create_user'=>$this->userInfo['id'],
              'update_time'=>time(),
          ];
          $id= Db::connect('company')->name($this->table)->strict(false)->field(true)->insertGetId($outData);

          $mxData=[
              'out_receipt_id'=>$id,
              'material_dossier_id'=>$this->param['mdId'],
              'num'=>$this->param['num'],
              'warehouse_id'=>$this->param['wId'],
              'locator'=>$this->param['locator']??1,
              'o_remark'=>$this->param['o_remark']??'',
              'create_time'=>time(),
              'update_time'=>time()
          ];
          Db::connect('company')->name('out_receipt_detail')->save($mxData);
          $sures=OutReceiptSever::doSure(['id'=>$id],$this->userInfo['id']);
          if ($sures['code']==1){
              throw new Exception($sures['msg']);
          }
          Db::connect('company')->commit();
      }catch (\Exception $e){
          Db::connect('company')->rollback();
          return $this->jump(0,$e->getMessage());
      }
      return $this->jump(1,'操作成功');
    }
}